package ltd.hello.trik.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

public class PageUtil {

	public static String pageUrl(String url, int pageIndex, int pageSize, Map<String, Object> map) throws IOException {
		StringBuilder sb = new StringBuilder(url);
		sb.append("?pageIndex=").append(pageIndex);
		sb.append("&pageSize=").append(pageSize);
		if (map!=null) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				String key = entry.getKey();
				Object value = entry.getValue();
				// TODO如果JS完成了encode，则此处不需要encode
				sb.append("&").append(key).append("=").append(URLEncoder.encode(value.toString(), "utf-8"));
			}
		}
		return sb.toString();
	}

	public static String pageUrlWithOutPage(String url, Map<String, Object> map) throws IOException {
		StringBuilder sb = new StringBuilder(url);
		if(map != null && map.size()>0){
			sb.append("?");
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				String key = entry.getKey();
				Object value = entry.getValue();
				// TODO如果JS完成了encode，则此处不需要encode
				sb.append("&").append(key).append("=").append(URLEncoder.encode(value.toString(), "utf-8"));
			}
		}
		return sb.toString();
	}

	public static String setUrl(String url, Map<String, Object> map) throws IOException {
		StringBuilder sBuilder = new StringBuilder(url);
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (sBuilder.indexOf("?") > -1) {
				sBuilder.append("&").append(key).append("=").append(URLEncoder.encode(value.toString(), "utf-8"));
			} else {
				sBuilder.append("?").append(key).append("=").append(URLEncoder.encode(value.toString(), "utf-8"));
			}
		}
		return sBuilder.toString();
	}

}
